import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import '/api/Api.dart';
import '/model/User.dart';

class CaseSecondPage extends StatefulWidget {
  Map? arguments;
  CaseSecondPage({this.arguments});

  @override
  _CaseSecondPageState createState() =>
      _CaseSecondPageState(arguments: this.arguments);
}

class _CaseSecondPageState extends State<CaseSecondPage> {
  Map? arguments;
  _CaseSecondPageState({this.arguments});

  late File _image;
  final picker = ImagePicker();
  List<File> mFlieList = [];

  String? historyStr;
  List<int> habitsList = [];

  TextEditingController nameController = TextEditingController();
  TextEditingController idController = TextEditingController();
  TextEditingController phonenumController = TextEditingController();
  TextEditingController ageController = TextEditingController();
  TextEditingController habitStrController = TextEditingController(text: '无');
  TextEditingController historyController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    nameController.text = arguments!['name'];
    idController.text = arguments!['idNum'];
    phonenumController.text = arguments!['phoneNum'];
    ageController.text = arguments!['age'];

    if (arguments!['history']) {
      historyController.text = '有';
      arguments!['history'] = 'y';
    } else {
      historyController.text = '无';
      arguments!['history'] = 'n';
    }

    if (arguments!['drink']) {
      if (habitStrController.text == '无') {
        habitStrController.text = '';
        habitStrController.text = habitStrController.text + ' 喝酒';
      } else {
        habitStrController.text = habitStrController.text + ' 喝酒';
      }
      habitsList.add(2);
    }

    if (arguments!['smoke']) {
      if (habitStrController.text == '无') {
        habitStrController.text = '';
        habitStrController.text = habitStrController.text + ' 抽烟';
      } else {
        habitStrController.text = habitStrController.text + ' 抽烟';
      }
      habitsList.add(1);
    }

    if (arguments!['stayup']) {
      if (habitStrController.text == '无') {
        habitStrController.text = '';
        habitStrController.text = habitStrController.text + ' 熬夜';
      } else {
        habitStrController.text = habitStrController.text + ' 熬夜';
      }
      habitsList.add(3);
    }

    arguments!['habits'] = habitsList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('基本信息'),
        ),
        body: SingleChildScrollView(
          child: Container(
            alignment: Alignment.center,
            margin: const EdgeInsets.all(20),
            padding: const EdgeInsets.all(5),
            child: Column(
              children: <Widget>[
                Container(
                    margin: const EdgeInsets.all(10),
                    child: TextField(
                      enabled: false,
                      controller: nameController,
                      decoration: InputDecoration(
                          border: OutlineInputBorder(), labelText: '姓名'),
                    )),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    controller: idController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '身份证号'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: phonenumController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '联系电话'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: ageController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '年龄'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: habitStrController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '习惯'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: historyController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '过敏史'),
                  ),
                ),
                ImageWrap(),
                Container(
                  margin: const EdgeInsets.all(10),
                  child:
                      ElevatedButton(onPressed: getPhone, child: Text('选择照片')),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: ElevatedButton(
                      onPressed: _submitCase, child: Text('点击上传')),
                ),
              ],
            ),
          ),
        ));
  }

  Widget ImageWrap() {
    return Container(
      margin: EdgeInsets.only(top: 30),
      child: Wrap(
        runSpacing: 5,
        spacing: 10,
        children: initFile(),
      ),
    );
  }

  initFile() {
    return mFlieList
        .map((file) => Stack(
              children: <Widget>[
                ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                  child: Image.file(
                    file,
                    width: 100,
                    height: 100,
                    fit: BoxFit.fill,
                  ),
                ),
                Positioned(
                    right: 0,
                    top: 0,
                    child: Container(
                      width: 30,
                      height: 30,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(15)),
                          color: Colors.black38),
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            mFlieList.remove(file);
                          });
                        },
                        child: Icon(
                          Icons.delete,
                          color: Colors.white,
                          size: 18,
                        ),
                      ),
                    ))
              ],
            ))
        .toList();
  }

  void getPhone() {
    showModalBottomSheet(
        // backgroundColor: Colors.tealAccent,
        //点击时底部面板颜色
        // barrierColor: Colors.amber,
        //点击时,底部面板以外的颜色
        shape: RoundedRectangleBorder(
            //设置样式
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20), topRight: Radius.circular(20))),
        isScrollControlled: false,
        //true 全屏 false 半屏
        isDismissible: true,
        //true外部可以点击  false外部不可以点击
        elevation: 40,
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 140,
            child: ListView(
              children: [
                Column(
                  children: [
                    _item("拍照", false, "拍照哦"),
                    _item("从相册选择", true, "选取照片哦"),
                  ],
                ),
              ],
            ),
          );
        });
  }

  _item(String title, bool bool, String subTitle) {
    return GestureDetector(
      child: ListTile(
        tileColor: Colors.teal, //背景色会把圆角覆盖掉!!
        //背景色
        subtitle: Text(subTitle),
        //副标题
        dense: true,
        //将字体缩小
        leading: Icon(
          bool ? Icons.ac_unit_outlined : Icons.add,
          size: 25,
        ),
        //左边显示图片
        trailing: Icon(Icons.android),
        //末尾显示图片
        contentPadding: EdgeInsets.all(3),
        //内边距 默认16
        title: Text(
          title,
        ),
        onTap: () {
          //短按
          setState(() {
            getImage(bool);
          });
        },
        onLongPress: () {
          //长按
        },
        selected: true, //如果选中,则颜色会跟随主题颜色
        enabled: true, //禁止点击事件
      ),
    );
  }

  Future getImage(bool bol) async {
    Navigator.pop(context);
    final pickedFile = await picker.getImage(
        source: bol ? ImageSource.gallery : ImageSource.camera);

    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
        print("SZJ本地图片路径为:${_image}");
        mFlieList.add(_image);
      } else {
        print('No image selected.');
      }
    });
  }

  Future _submitCase() async {
    if (mFlieList.length < 3) {
      Fluttertoast.showToast(
        msg: '请选择至少三张主动脉图片',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
      return;
    }

    arguments!['photos'] = mFlieList;
    Navigator.pop(context);
    Navigator.pop(context);
    print('全部参数：${arguments.toString()}');

    Navigator.pushNamed(context, '/post_case', arguments: arguments);
  }
}
